<template>
<div id="register">
    <el-form v-model="register_data" label-width="25%">
        <el-form-item>
            <h1 style="margin-left: 25%">注册</h1>
        </el-form-item>
        <el-form-item label="邮箱">
            <el-input v-model="register_data.username" style="width: 65%"></el-input>
        </el-form-item>
        <el-form-item label="密码">
            <el-input type="password" v-model="register_data.password" style="width: 65%"></el-input>
        </el-form-item>
        <el-form-item label="请确认密码">
            <el-input type="password" v-model="register_data.password" style="width: 65%"></el-input>
        </el-form-item>
        <el-form-item label="验证码">
            <el-input v-model="register_data.code" style="width: 25%"></el-input>
            <el-button style="margin-left: 8%;width: 32%" :loading="loading" @click="getEmailCode">{{msg}}</el-button>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" style="width: 20%" :disabled="register_check" @click="register">注册</el-button>
            <router-link to="/login" style="margin-left: 26%"><el-button type="primary">返回登录</el-button></router-link>
        </el-form-item>
    </el-form>
</div>
</template>

<script>
    export default {
        name: "Register",
        data(){
            return{
                register_data:{
                    username:'',
                    password:'',
                    code:''
                },
                loading: false,
                register_check: true,
                msg:'点击发送验证码',
            }
        },
        methods:{
            sendCode(x){
                let timer = setInterval(() =>{
                    if(x==0){
                        this.loading=false
                        this.msg='点击发送验证码'
                        timer=clearInterval(timer)
                        return;
                    }
                    this.msg=x+'秒后可重新发送'
                    x--
                }, 1000)
            },
            getEmailCode(){
                this.loading=true
                this.register_check=false
                this.axios.post("/register/getEmailCode",{
                    username:this.register_data.username
                })
                this.sendCode(60)

            },
            register(){
                this.axios.post("/register",this.register_data)
                    .then(function (response) {
                        if(response.data.code==100){
                            alert("注册成功，请登录")
                            this.$router.push('/login');
                        }
                        else {
                            alert("验证码错误")
                        }
                })
            }
        }
    }
</script>

<style>
#register{
    background: #fcfcfc;
    margin: 0 auto;
    margin-top: 10%;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
    width: 700px;
    height: 600px;
}
</style>
